<template>
<div class="card">
    <el-form class="form">
      <el-form-item>
        <el-input v-model="data.orderNum" placeholder="请输入订单编号" width="200px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadOrderList">查询</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
</div>
  <div class="card">
  <el-table :data="data.ordersList" stripe style="width: 100%">
    <!-- 订单编号 -->
    <el-table-column prop="orderNumber" label="订单编号" width="180" align="center" fixed="left"></el-table-column>

    <!-- 订单状态 -->
    <el-table-column prop="orderStatus" label="订单状态" width="120" align="center" fixed="left">
      <template #default="scope">
        <el-tag :type="getStatusTagType(scope.row.orderStatus)">
          {{ getStatusText(scope.row.orderStatus) }}
        </el-tag>
      </template>
    </el-table-column>


    <!-- 订单总价 -->
    <el-table-column prop="totalPrice" label="订单总价" width="120" align="center">
      <template #default="scope">
        {{ formatPrice(scope.row.totalPrice) }}
      </template>
    </el-table-column>

    <!-- 支付方式 -->
    <el-table-column prop="paymentMethod" label="支付方式" width="120" align="center">
      <template #default="scope">
        {{ getPaymentMethodText(scope.row.paymentMethod) }}
      </template>
    </el-table-column>
    <!-- 生成订单员工姓名 -->
    <el-table-column prop="userName" label="生成订单员工姓名" width="120" align="center"></el-table-column>
<!--    订单详情按钮-->
    <el-table-column label="查看订单详情" width="180" align="center">
      <template v-slot="scope">
        <el-button type="primary" size="small" @click="handleloadDetails(scope.row)">查看订单详情</el-button>
      </template>
    </el-table-column>
    <!-- 下单日期 -->
    <el-table-column prop="orderCreateDate" label="下单日期" width="180" align="center"></el-table-column>


    <!-- 订单状态修改人 -->
    <el-table-column prop="updateUserName" label="申请退货的员工姓名" width="120" align="center"></el-table-column>

    <!-- 订单状态修改日期 -->
    <el-table-column prop="orderUpdateDate" label="修改日期" width="180" align="center"></el-table-column>


    <!-- 退货原因 -->
    <el-table-column prop="returnReason" label="退货原因" width="200" align="center"></el-table-column>
    <el-table-column prop="refuseReturnReason" label="拒绝退货原因" width="200" align="center"></el-table-column>

    <!-- 操作列 -->
    <el-table-column label="操作" width="180" align="center" fixed="right">
      <template #default="scope">
        <el-button type="danger" size="small" @click="operation('return',scope.row)" v-if="scope.row.orderStatus ==='1'">申请退货</el-button>
        <el-button type="danger" size="small" @click="operation('updateStatus',scope.row)" v-if="scope.row.orderStatus ==='0'">修改支付状态</el-button>
      </template>
    </el-table-column>
  </el-table>
    <div class="pagination">

      <el-pagination
          style="margin-top: 5px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="data.pageNum"
          :page-sizes="[3, 5, 10, 15, 20]"
          :page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total">

      </el-pagination>
    </div>
  </div>


  <!-- 订单详情Dialog-->
  <el-dialog v-model="data.dialogVisible" title="订单详情" width="60%" center>
    <el-table :data="data.orderDetailsList" stripe style="width: 100%; margin-top: 20px;">
      <el-table-column prop="productName" label="药品名称"></el-table-column>
      <el-table-column label="药品图片">
        <template #default="scope">
          <img :src="scope.row.imageUrl" alt="药品图片" class="product-image">
        </template>
      </el-table-column>
      <el-table-column prop="price" label="药品单价"></el-table-column>
      <el-table-column prop="quantity" label="购买数量"></el-table-column>
      <el-table-column prop="totalPrice" label="总价格"></el-table-column>
    </el-table>
    <div class="dialog-footer">
      <el-button type="danger" @click="data.dialogVisible = false" class="close-button">关闭</el-button>
    </div>
  </el-dialog>

  <el-dialog v-model="data.returnVisible" :title="data.title" width="50%">
    <el-form :model="data.formData" label-width="120px" style="padding: 20px;" :rules="data.rules">
      <el-form-item label="退货原因" prop="returnReason" v-if="data.operation === 'handelReturn'">
        <el-input
            v-model="data.formData.returnReason"
            placeholder="请输入退货原因"
            type="textarea"
            style="width: 100%; max-width: 600px;"
        ></el-input>
      </el-form-item>

      <el-form-item label="请选择支付方式" v-if="data.operation === 'handelUpdateStatus'">
        <el-select
            v-model="data.formData.paymentMethod"
            style="width: 100%; max-width: 300px;"
        >
          <el-option label="微信支付" :value="1"></el-option>
          <el-option label="支付宝支付" :value="2"></el-option>
          <el-option label="现金支付" :value="3"></el-option>
          <el-option label="银行卡支付" :value="4"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item style="text-align: right; margin-top: 20px;">
        <el-button type="danger" @click="cancelReturn">取消</el-button>
        <el-button type="primary" @click="operation(data.operation, data.formData)" style="margin-left: 10px;">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>
<script setup>
import { ref ,reactive} from "vue";
import {loadOrderDetailApi, loadOrderListApi, updateOrderStatusApi} from "@/utils/API/orders/manageOrder";
import {ElMessage} from "element-plus";

const data =reactive({
  ordersList:[],
  order:{},
  pageNum:1,
  pageSize:10,
  total:0,
  userName:'',
  dialogVisible:false,
  orderDetailsList:[],
  returnVisible:false,
  orderNum:'',
  user:JSON.parse(localStorage.getItem('system-user')||'{}'),
  title:'',
  operation:'',
  formData:{
    paymentMethod:{
      label:'微信支付',
      value:'1'
    }
  },
  rules:{
    returnReason: [
      { required: true, message: '请输入退货原因', trigger: 'blur' },
      { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
    ],
    paymentMethod: [
      { required: true, message: '请选择支付方式', trigger: 'blur' }
    ]
  },
})

const loadOrderList =()=>{
  let params ={
       orderNumber :data.orderNum,
       pageNum:data.pageNum,
       pageSize:data.pageSize
  }
loadOrderListApi(params).then(res=>{
  if(res.code==='200'){
    data.total = res.data?.total
    data.ordersList=res.data?.list

  }else{
    ElMessage.error(res.msg)
  }
})
}
loadOrderList()

const loadByOrderNum =()=>{
  let params ={

    pageNum:data.pageNum,
    pageSize:data.pageSize
  }

}
// 处理页码改变
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize;
  loadOrderList()
};

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum;
  loadOrderList()
};
// 格式化价格
const formatPrice = (price) => {
  return `￥${price.toFixed(2)}`;
};

// 获取订单状态文本
const getStatusText = (status) => {
  switch (status) {
    case '0':
      return "未支付";
    case '1':
      return "已支付";
    case '2':
      return "退货中";
    case '3':
      return "退货成功";
    default:
      return "拒绝退货";
  }
};

// 获取订单状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '0':
      return "warning";
    case '1':
      return 'success';
    case '2':
      return "info";
    case '3':
      return "danger";
    default:
      return "";
  }
};

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  switch (method) {
    case '0':
      return "未支付";
    case '1':
      return "微信支付";
    case '2':
      return "支付宝支付";
    case '3':
      return "现金支付";
      case '4':
        return "银行卡支付";
        default:
          return "未知支付方式";
  }
};

// 编辑操作
const handleEdit = (row) => {
  console.log("编辑订单:", row);
};

// 删除操作
const handleloadDetails = (row) => {
  let  param ={
    orderId:row.orderId
  }
  loadOrderDetailApi(param).then(res=>{
    if (res.code==='200'){
      data.orderDetailsList = processDetails(res.data.orderProducts)
      data.dialogVisible = true
      console.log(res)
      console.log(data.orderDetailsList)
    }else {
      ElMessage.error(res.msg)
    }
})
};
const processDetails = (products) => {
  return products.map(item => {
    return {
      ...item.product,
      quantity: item.quantity,
      totalPrice: item.product.price * item.quantity
    };
  });
};

const operation = (op,row) => {
  console.log("申请退货:", row);
  data.returnVisible = true;
  data.formData = row
  switch (op){
    case 'return':
      data.returnVisible = true;
      data.title = '退货申请'
        data.operation = 'handelReturn'
      break;
      case 'updateStatus':
        data.title = '修改订单状态'
        data.operation = 'handelUpdateStatus'
        break;
    case 'handelReturn' :
      handelReturn();
      break;
      case 'handelUpdateStatus' :
        handelUpdateStatus();
        break;

  }

};
const cancelReturn = () => {
  data.returnVisible = false;
  data.formData = {};
};

const handelReturn = () => {
  data.formData.orderStatus = '2'
  data.formData.updateUserName = data.user.name
  data.formData.orderUpdateDate = formateDate()
  console.log("data.formData",data.formData)
 updateOrderStatusApi(data.formData).then(res=>{
   if(res.code ==='200'){
     ElMessage.success("提交申请成功，等待管理员审核")
     loadOrderList()
     data.returnVisible = false
   }else{
     ElMessage.error(res.msg)
   }
 })
};
/**
 * 修改订单状态
 * @param row
 */
const handelUpdateStatus =()=>{
  data.formData.orderStatus = '1'
  data.formData.updateUserName = data.user.name
  data.formData.orderUpdateDate = formateDate()
  updateOrderStatusApi(data.formData).then(res=>{
    if(res.code ==='200'){
      ElMessage.success("提交申请成功，等待商家审核")
      loadOrderList()
      data.returnVisible = false
    }else{
      ElMessage.error(res.msg)
    }
  })
}
const formateDate =()=>{
  const date = new Date();  // 获取当前时间
  const year = date.getFullYear();  // 获取年份
  const month = String(date.getMonth() + 1).padStart(2, '0');  // 获取月份，注意需要 +1
  const day = String(date.getDate()).padStart(2, '0');  // 获取日期
  const hours = String(date.getHours()).padStart(2, '0');  // 获取小时
  const minutes = String(date.getMinutes()).padStart(2, '0');  // 获取分钟
  const seconds = String(date.getSeconds()).padStart(2, '0');  // 获取秒数

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const reset = () => {
  data.orderNum = "";
  loadOrderList()
};
</script>
<style scoped>
/* 表单样式 */
.form {
  display: flex;
  align-items: center;
}

.form .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.form .el-input {
  width: 200px;
}

/* 表格样式 */
.card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.el-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

.el-table td {
  padding: 12px 0;
}

.el-table .el-tag {
  margin: 2px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 订单详情Dialog */
.el-dialog {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.el-dialog__body {
  padding: 24px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.close-button {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.close-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 退货Dialog */
.el-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input, .el-textarea, .el-select {
  width: 100%;
  max-width: 600px;
}

.el-textarea__inner {
  border-radius: 8px;
  padding: 10px;
}

.el-select {
  width: 100%;
  max-width: 300px;
}

.el-button {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #ffffff;
}

.el-button--danger:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>